﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DevExpress.Spreadsheet;
using DevExpress.Web.Mvc;

namespace SpreadSheetViewer.Controllers
{
    public class ReportController : Controller
    {
        // GET: ReportViewer
        public ActionResult Viewer()
        {
            return View("Viewer");
        }
        // GET: ReportViewer
        public ActionResult Designer()
        {
            return View("Designer");
        }

        IWorkbook CurrentDocument
        {
            get
            {
                return DevExpress.Web.Mvc.SpreadsheetExtension.GetCurrentDocument("spreadsheet");
            }
        }
        Worksheet CurrentWorksheet
        {
            get
            {
                return CurrentDocument.Worksheets.ActiveWorksheet;
            }
        }

        //public ActionResult SpreadSheetsInit()
        //{
        //    return View("Index");
        //}

        public ActionResult SpreadCalcbackCommand(string command, string param)
        {
            switch (command.ToUpper().Trim())
            {
                case "OPEN":
                    return OpenFile(param);
                case "CREATE":
                    return CreateNew();
                case "FORMULA":
                    return AddFormula(param);
                default:
                    return null;
            }
        }

        private ActionResult AddFormula(string param)
        {
            if (Session["Spread"] is IWorkbook document)
            {
                Newtonsoft.Json.Linq.JObject o = Newtonsoft.Json.Linq.JObject.Parse(param);
                var col = o["col"].ToString();
                int colNum;
                int.TryParse(col, out colNum);
                var row = o["row"].ToString();
                int rowNum;
                int.TryParse(row, out rowNum);
                var formula = o["formula"].ToString();
                CurrentWorksheet.Columns[colNum][rowNum].Formula = formula;
                //return value;
                return PartialView("SpreadSheetViewerPartial");
            }
            return null;
        }

        public ActionResult DownloadFile(string fileType)
        {
            if (Session["Spread"] is IWorkbook document)
            {
                List<Tuple<string, Cell>> records = new List<Tuple<string, Cell>>();
                foreach (var sheet in document.Worksheets)
                {
                    foreach (var cell in sheet.GetExistingCells())
                    {
                        if (!string.IsNullOrWhiteSpace(cell.Formula))
                        {
                            records.Add(new Tuple<string, Cell>(cell.Formula, cell));
                            cell.Value = cell.Value;
                            cell.Formula = string.Empty;
                        }
                    }
                }
                byte[] bytes = null;
                string extString = "";
                switch (fileType.ToUpper())
                {
                    case "PDF":
                        var stream = new System.IO.MemoryStream();
                        document.ExportToPdf(stream);
                        bytes = stream.ToArray();
                        extString = "pdf";
                        break;
                    case "XLS":
                        bytes = document.SaveDocument(DocumentFormat.Xls);
                        extString = "xls";
                        break;
                    case "CSV":
                        bytes = document.SaveDocument(DocumentFormat.Csv);
                        extString = "csv";
                        break;
                    case "XLSX":
                    default:
                        bytes = document.SaveDocument(DocumentFormat.Xlsx);
                        extString = "xlsx";
                        break;
                }
                foreach (var record in records)
                {
                    record.Item2.Formula = record.Item1;
                }
                string fileNameTemp = "exportFile." + extString;
                var result = File(bytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileNameTemp);
                return result;
            }
            else
                return null;
        }
        private ActionResult OpenFile(string filePath)
        {
            var res = DevExpress.Web.Mvc.SpreadsheetExtension.Open("spreadsheet", System.IO.Path.Combine(Helper.DirectoryManagmentUtils.CurrentDataDirectory, filePath));
            Session["Spread"] = CurrentDocument;
            CurrentDocument.Options.CalculationMode = WorkbookCalculationMode.Manual;
            return res;
        }
        private ActionResult CreateNew()
        {
            var res = DevExpress.Web.Mvc.SpreadsheetExtension.New("spreadsheet");
            Session["Spread"] = CurrentDocument;
            CurrentDocument.Options.CalculationMode = WorkbookCalculationMode.Manual;
            return res;
        }
        public ActionResult SpreadSheetViewerPartial()
        {
            return PartialView("SpreadSheetViewerPartial");
        }
        public ActionResult SpreadSheetDesignerPartial()
        {
            return PartialView("SpreadSheetDesignerPartial");
        }
        [ValidateInput(false)]
        public ActionResult FileManagePartial()
        {
            return PartialView("FileManagePartial");
        }
        public FileStreamResult DownloadFiles()
        {
            DevExpress.Web.FileManagerSettingsEditing editingSettings = new DevExpress.Web.FileManagerSettingsEditing(null)
            {
                AllowCreate = true,
                AllowMove = true,
                AllowDelete = true,
                AllowRename = true,
                AllowCopy = true,
                AllowDownload = true
            };
            var settings = new DevExpress.Web.Mvc.FileManagerSettings();
            settings.SettingsEditing.Assign(editingSettings);
            settings.Name = "fileManager";
            return FileManagerExtension.DownloadFiles(settings, Helper.DirectoryManagmentUtils.DocumentBrowsingFolderPath);
        }
        //public ActionResult FileManage()
        //{
        //    return View("FileManage");
        //}
    }
}